<template>
  <view class="message-container">
    <!-- 顶部搜索栏 -->
    <view class="search-header">
      <view class="search-box" @click="goToSearch">
        <text class="search-icon">S</text>
        <text class="search-placeholder">搜索联系人、群聊</text>
      </view>
      <view class="add-btn" @click="showAddMenu">
        <text class="add-icon">+</text>
      </view>
    </view>

    <!-- 功能入口 -->
    <view class="function-section">
      <view class="function-list">
        <view class="function-item" @click="goToFriends">
          <view class="function-icon friends">
            <image class="icon-image" src="http://8.145.55.161:19000/logo/tongxunlu_1.png" mode="aspectFit" />
          </view>
          <text class="function-name">好友</text>
          <view v-if="friendRequests > 0" class="badge">{{ friendRequests }}</view>
        </view>
<!--        <view class="function-item" @click="goToGroups">-->
<!--          <view class="function-icon friends">-->
<!--            <image class="icon-image" src="http://8.145.55.161:19000/logo/group.png" mode="aspectFit" />-->
<!--          </view>-->
<!--          <text class="function-name">群聊</text>-->
<!--          <view v-if="friendRequests > 0" class="badge">{{ friendRequests }}</view>-->
<!--        </view>-->
        <view class="function-item" @click="goToAiChat">
          <view class="function-icon friends">
            <image class="icon-image" src="http://8.145.55.161:19000/logo/aikefu_1.png" mode="aspectFit" />
          </view>
          <text class="function-name">AI助手</text>
        </view>
        <view class="function-item" @click="goToNotifications">
          <view class="function-icon notifications">
            <image class="icon-image" src="http://8.145.55.161:19000/logo/tongzhizhongxin.png" mode="aspectFit" />
          </view>
          <text class="function-name">通知</text>
          <view v-if="notificationCount > 0" class="badge">{{ notificationCount }}</view>
        </view>
      </view>
    </view>

    <!-- 会话列表 -->
    <view class="conversation-section">
      <view class="section-header">
        <text class="section-title">最近会话</text>
        <view class="header-actions">
          <text class="refresh-btn" @click="refreshConversations">刷新</text>
          <text class="clear-btn" @click="clearAllConversations">清空</text>
        </view>
      </view>

      <!-- 下拉刷新的会话列表 -->
      <scroll-view
        class="conversation-scroll"
        scroll-y="true"
        :refresher-enabled="true"
        :refresher-triggered="isRefreshing"
        @refresherrefresh="onRefresh"
      >
        <!-- 置顶会话 -->
        <view v-if="pinnedConversations.length > 0" class="pinned-conversations">
          <view
              v-for="(conversation, index) in pinnedConversations"
              :key="'pinned-' + conversation.id"
              class="conversation-item pinned"
              @click="openChat(conversation)"
              @longpress="showConversationMenu(conversation)"
          >
            <view class="avatar-container">
              <image class="avatar" :src="conversation.avatar" mode="aspectFill" @error="onAvatarError" />
              <view v-if="conversation.isOnline" class="online-status"></view>
            </view>
            <view class="conversation-info">
              <view class="conversation-header">
                <text class="conversation-name">{{ conversation.name }}</text>
                <text class="conversation-time">{{ formatTime(conversation.lastMessageTime) }}</text>
              </view>
              <view class="conversation-content">
                <text class="last-message">{{ formatLastMessage(conversation.lastMessage) }}</text>
                <view v-if="conversation.unreadCount > 0" class="unread-badge">
                  {{ conversation.unreadCount > 99 ? '99+' : conversation.unreadCount }}
                </view>
              </view>
            </view>
            <view class="pin-icon">•</view>
          </view>
        </view>

        <!-- 普通会话 -->
        <view class="normal-conversations">
          <view
              v-for="(conversation, index) in normalConversations"
              :key="conversation.id"
              class="conversation-item"
              @click="openChat(conversation)"
              @longpress="showConversationMenu(conversation)"
          >
            <view class="avatar-container">
              <image class="avatar" :src="conversation.avatar" mode="aspectFill" @error="onAvatarError" />
              <view v-if="conversation.isOnline" class="online-status"></view>
            </view>
            <view class="conversation-info">
              <view class="conversation-header">
                <text class="conversation-name">{{ conversation.name }}</text>
                <text class="conversation-time">{{ formatTime(conversation.lastMessageTime) }}</text>
              </view>
              <view class="conversation-content">
                <text class="last-message">{{ formatLastMessage(conversation.lastMessage) }}</text>
                <view v-if="conversation.unreadCount > 0" class="unread-badge">
                  {{ conversation.unreadCount > 99 ? '99+' : conversation.unreadCount }}
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="conversations.length === 0 && !isLoading" class="empty-state">
          <ob-empty
              :image="'/static/images/empty-message.png'"
              title="暂无会话"
              description="开始与朋友聊天吧"
          />
        </view>
      </scroll-view>
    </view>

    <!-- 添加菜单弹窗 -->
    <view v-if="showAddModal" class="add-modal" @click="showAddModal = false">
      <view class="add-menu" @click.stop>
        <view class="add-option" @click="addFriend">
          <text class="option-icon">+</text>
          <text class="option-text">添加好友</text>
        </view>
<!--        <view class="add-option" @click="createGroup">-->
<!--          <text class="option-icon">C</text>-->
<!--          <text class="option-text">创建群聊</text>-->
<!--        </view>-->
<!--        <view class="add-option" @click="joinGroup">-->
<!--          <text class="option-icon">J</text>-->
<!--          <text class="option-text">搜索群聊</text>-->
<!--        </view>-->
      </view>
    </view>

    <!-- 会话菜单弹窗 -->
    <view v-if="showContextMenu" class="context-modal" @click="showContextMenu = false">
      <view class="context-menu" @click.stop>
        <view class="menu-option" @click="togglePin">
          <text class="option-text">{{ selectedConversation?.isPinned ? '取消置顶' : '置顶会话' }}</text>
        </view>
        <view class="menu-option" @click="markAsRead">
          <text class="option-text">标记已读</text>
        </view>
        <view class="menu-option" @click="muteConversation">
          <text class="option-text">{{ selectedConversation?.isMuted ? '取消免打扰' : '免打扰' }}</text>
        </view>
        <view class="menu-option delete" @click="deleteConversation">
          <text class="option-text">删除会话</text>
        </view>
      </view>
    </view>

    <!-- 加载组件 -->
    <ob-loading :visible="isLoading" text="加载中..." />
  </view>
</template>

<script setup>
import { ref, computed, inject, onMounted, onUnmounted } from 'vue'
import { formatDistanceToNow } from '../../utils/common.js'
import messageApi from '../../api/message.js'
import friendApi from '../../api/friend.js'
import { userApi } from '../../api/user.js'

// 全局状态
const store = inject('$store')

// 响应式数据
const conversations = ref([])
const friendRequests = ref(0)
const notificationCount = ref(0)
const isLoading = ref(false)
const isLoadingCounts = ref(false) // 防止重复加载计数
const isRefreshing = ref(false) // 下拉刷新状态
const showAddModal = ref(false)


const showContextMenu = ref(false)
const selectedConversation = ref(null)

// 计算属性
const pinnedConversations = computed(() => {
  return conversations.value.filter(conv => conv.isPinned)
})

const normalConversations = computed(() => {
  return conversations.value.filter(conv => !conv.isPinned)
})

// 页面生命周期
onMounted(() => {
  loadConversations()
  loadCounts()
  // 开启消息监听
  startMessageListener()

  // 动态加载 FastGPT 脚本
  loadFastGPTScript()

  // 添加全局点击事件监听，确保聊天窗口外点击时关闭
  document.addEventListener('click', handleGlobalClick)
})

// 全局点击处理
const handleGlobalClick = (event) => {
  const chatWindow = document.getElementById('fastgpt-chatbot-window')
  const chatBtn = document.getElementById('fastgpt-chatbot-button')

  if (chatWindow && chatBtn &&
      chatWindow.style.visibility !== 'hidden' &&
      chatWindow.style.display !== 'none') {

    // 检查点击是否在聊天窗口或按钮外部
    if (!chatWindow.contains(event.target) && !chatBtn.contains(event.target)) {
      // 可选：点击外部区域关闭聊天窗口
      // chatWindow.style.visibility = 'hidden'
      // chatWindow.style.display = 'none'
      // const img = chatBtn.querySelector('img')
      // if (img) {
      //   img.src = document.getElementById('chatbot-iframe')?.getAttribute('data-open-icon')
      // }
    }
  }
}

onUnmounted(() => {
  // 停止消息监听
  stopMessageListener()

  // 清理全局事件监听
  document.removeEventListener('click', handleGlobalClick)

  // 清理 FastGPT 相关元素
  const chatBtn = document.getElementById('fastgpt-chatbot-button')
  const chatWindow = document.getElementById('fastgpt-chatbot-window')
  const script = document.getElementById('chatbot-iframe')

  if (chatBtn) chatBtn.remove()
  if (chatWindow) chatWindow.remove()
  if (script) script.remove()
})

// 加载 FastGPT 脚本
const loadFastGPTScript = () => {
  // 检查脚本是否已经存在
  const existingScript = document.getElementById('chatbot-iframe')
  if (existingScript) return

  // 创建脚本元素
  const script = document.createElement('script')
  script.type = 'text/javascript'
  script.src = 'https://cloud.fastgpt.cn/js/iframe.js'
  script.id = 'chatbot-iframe'
  script.defer = true
  // script.setAttribute('data-bot-src', 'https://cloud.fastgpt.cn/chat/share?shareId=vlp05iMXKn7q0wtTYNZo2NfI')
  script.setAttribute('data-bot-src', 'https://cloud.fastgpt.cn/chat/share?shareId=vYtupIy6ortzgjk9j1m5jdAM')
  script.setAttribute('data-default-open', 'false')
  script.setAttribute('data-drag', 'false')
  // 方案一：使用机器人图标 SVG
  // script.setAttribute('data-open-icon', '')
  // script.setAttribute('data-close-icon', '')

  // 方案二：使用本地图片文件（取消注释下面两行来使用）
  script.setAttribute('data-open-icon', 'http://8.145.55.161:19000/logo/aikefu-copy.png')
  script.setAttribute('data-close-icon', 'http://8.145.55.161:19000/logo/guanbi_X.png')

  // 方案三：使用 Emoji 风格图标（取消注释下面两行来使用）
  // script.setAttribute('data-open-icon', '')
  // script.setAttribute('data-close-icon', '')

  // 脚本加载完成后手动调用 embedChatbot
  script.onload = () => {
    console.log('FastGPT 脚本已加载')
    // 延迟一点时间确保脚本完全执行
    setTimeout(() => {
      if (window.embedChatbot && typeof window.embedChatbot === 'function') {
        window.embedChatbot()
        console.log('FastGPT 聊天机器人已初始化')
        // 调整按钮位置
        adjustChatButtonPosition()
      } else {
        console.warn('embedChatbot 函数未找到，尝试手动初始化')
        initFastGPTManually()
      }
    }, 100)
  }

  script.onerror = () => {
    console.error('FastGPT 脚本加载失败')
  }

  document.body.appendChild(script)
}

// 调整聊天按钮位置
const adjustChatButtonPosition = () => {
  setTimeout(() => {
    const chatBtn = document.getElementById('fastgpt-chatbot-button')
    const chatWindow = document.getElementById('fastgpt-chatbot-window')

    if (chatBtn) {
      // 调整按钮位置和样式
      chatBtn.style.bottom = '80px'
      chatBtn.style.right = '20px'
      chatBtn.style.width = '50px'
      chatBtn.style.height = '50px'
      chatBtn.style.borderRadius = '50%'
      chatBtn.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)'
      chatBtn.style.transition = '0.3s'

      // 重新绑定点击事件以确保关闭功能正常
      const newChatBtn = chatBtn.cloneNode(true)
      chatBtn.parentNode.replaceChild(newChatBtn, chatBtn)

      newChatBtn.addEventListener('click', () => {
        const window = document.getElementById('fastgpt-chatbot-window')
        if (!window) return

        const img = newChatBtn.querySelector('img')
        if (window.style.visibility === 'hidden' || window.style.display === 'none') {
          window.style.visibility = 'unset'
          window.style.display = 'flex'
          if (img) {
            img.src = document.getElementById('chatbot-iframe')?.getAttribute('data-close-icon') || ''
          }
          console.log('聊天窗口已打开')
        } else {
          window.style.visibility = 'hidden'
          window.style.display = 'none'
          if (img) {
            img.src = document.getElementById('chatbot-iframe')?.getAttribute('data-open-icon') || ''
          }
          console.log('聊天窗口已关闭')
        }
      })

      console.log('聊天按钮位置已调整，关闭功能已修复')
    }

    if (chatWindow) {
      // 调整聊天窗口位置
      chatWindow.style.right = '20px'
      chatWindow.style.bottom = '80px'
      console.log('聊天窗口位置已调整')
    }
  }, 200)
}

// 手动初始化 FastGPT（备用方案）
const initFastGPTManually = () => {
  try {
    // 检查是否已经存在聊天按钮
    if (document.getElementById('fastgpt-chatbot-button')) {
      console.log('FastGPT 聊天按钮已存在')
      return
    }

    const script = document.getElementById('chatbot-iframe')
    const botSrc = script?.getAttribute('data-bot-src')

    if (!botSrc) {
      console.error('未找到 data-bot-src 属性')
      return
    }

    // 创建聊天按钮
    const chatBtn = document.createElement('div')
    chatBtn.id = 'fastgpt-chatbot-button'
    chatBtn.style.cssText = 'position: fixed; bottom: 20px; right: 20px; width: 50px; height: 50px; cursor: pointer; z-index: 2147483647; transition: 0.3s; border-radius: 50%; box-shadow: 0 4px 12px rgba(0,0,0,0.15);'

    const chatBtnImg = document.createElement('img')
    // chatBtnImg.src = script?.getAttribute('data-open-icon') || ''
    chatBtnImg.src =  '"C:\\Users\\lenovo\\Desktop\\images\\icon_fac456hve66\\aikefu-copy.png"'
    chatBtnImg.setAttribute('width', '100%')
    chatBtnImg.setAttribute('height', '100%')
    chatBtnImg.draggable = false

    // 创建聊天窗口
    const iframe = document.createElement('iframe')
    iframe.allow = 'microphone *; *'
    iframe.referrerPolicy = 'no-referrer'
    iframe.title = 'FastGPT Chat Window'
    iframe.id = 'fastgpt-chatbot-window'
    iframe.src = botSrc
    iframe.style.cssText = 'border: none; position: fixed; flex-direction: column; justify-content: space-between; box-shadow: rgba(150, 150, 150, 0.2) 0px 10px 30px 0px, rgba(150, 150, 150, 0.2) 0px 0px 0px 1px; width: 375px; height: 667px; max-width: 90vw; max-height: 85vh; border-radius: 0.75rem; display: flex; z-index: 2147483647; overflow: hidden; left: unset; background-color: #F3F4F6; right: 20px; bottom: 80px;'
    iframe.style.visibility = 'hidden'

    // 点击事件
    chatBtn.addEventListener('click', () => {
      const chatWindow = document.getElementById('fastgpt-chatbot-window')
      if (!chatWindow) return

      if (chatWindow.style.visibility === 'hidden' || chatWindow.style.display === 'none') {
        chatWindow.style.visibility = 'unset'
        chatWindow.style.display = 'flex'
        chatBtnImg.src = script?.getAttribute('data-close-icon') || ''
        console.log('聊天窗口已打开')
      } else {
        chatWindow.style.visibility = 'hidden'
        chatWindow.style.display = 'none'
        chatBtnImg.src = script?.getAttribute('data-open-icon') || ''
        console.log('聊天窗口已关闭')
      }
    })

    chatBtn.appendChild(chatBtnImg)
    document.body.appendChild(chatBtn)
    document.body.appendChild(iframe)

    console.log('FastGPT 聊天机器人手动初始化完成')
  } catch (error) {
    console.error('手动初始化 FastGPT 失败:', error)
  }
}

// 强制关闭聊天窗口的方法
const forceChatWindowClose = () => {
  const chatWindow = document.getElementById('fastgpt-chatbot-window')
  const chatBtn = document.getElementById('fastgpt-chatbot-button')

  if (chatWindow) {
    chatWindow.style.visibility = 'hidden'
    chatWindow.style.display = 'none'
    console.log('强制关闭聊天窗口')
  }

  if (chatBtn) {
    const img = chatBtn.querySelector('img')
    if (img) {
      img.src = document.getElementById('chatbot-iframe')?.getAttribute('data-open-icon') || ''
    }
  }
}

// 暴露强制关闭方法到全局，方便调试
if (typeof window !== 'undefined') {
  window.forceChatWindowClose = forceChatWindowClose
}

// 加载会话列表
const loadConversations = async () => {
  try {
    isLoading.value = true
    const response = await messageApi.getConversations()

    console.log('🔍 API原始响应:', response)

    // 处理不同的API响应格式
    let rawList = null
    if (response) {
      if (Array.isArray(response)) {
        rawList = response
      } else if (response.data && Array.isArray(response.data)) {
        rawList = response.data
      } else if (response.conversations && Array.isArray(response.conversations)) {
        rawList = response.conversations
      } else if (response.data && response.data.conversations && Array.isArray(response.data.conversations)) {
        rawList = response.data.conversations
      }
    }

    console.log('🔍 解析后的会话数据:', rawList)

    // 后端返回的是每个会话的最新消息（ChatMessage[]）
    const userInfo = uni.getStorageSync('userInfo') || {}
    const currentUserId = userInfo?.id || userInfo?.userId
    const currentUsername = userInfo?.username || userInfo?.nickname || 'user'

    console.log('=== 开始构建会话列表 ===')
    console.log('原始消息数量:', rawList?.length || 0)
    console.log('当前用户ID:', currentUserId)
    console.log('当前用户名:', currentUsername)
    console.log('原始数据示例:', rawList?.[0])

    // 默认头像URL
    const defaultAvatarUrl = 'https://ts1.tc.mm.bing.net/th/id/OIP-C.4qE6UmzbSk0mCOn2uWMELAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3'

    conversations.value = (rawList || []).map((msg, index) => {
      // 优先使用后端新增的targetName和targetAvatar字段
      let otherUsername, otherNickname, otherAvatar, otherUserId

      if (msg.targetName && msg.targetAvatar) {
        // 后端已经处理好了目标用户信息
        otherNickname = msg.targetName
        otherUsername = msg.targetName // 如果没有单独的username字段，使用targetName
        otherAvatar = msg.targetAvatar
        otherUserId = msg.fromId === currentUserId ? msg.toId : msg.fromId
      } else {
        // 回退到原有逻辑，使用用户ID来识别当前用户
        if (msg.fromId === currentUserId) {
          // 当前用户是发送方，对方是接收方
          otherUserId = msg.toId
          otherUsername = msg.toName
          otherNickname = msg.toName // 后端已经填充了真实昵称
          otherAvatar = msg.toAvatar || defaultAvatarUrl
        } else {
          // 当前用户是接收方，对方是发送方
          otherUserId = msg.fromId
          otherUsername = msg.fromName
          otherNickname = msg.fromName // 后端已经填充了真实昵称
          otherAvatar = msg.fromAvatar || defaultAvatarUrl
        }
      }

      const isRealAvatar = otherAvatar !== defaultAvatarUrl

      console.log(`会话 ${index + 1}: 用户ID=${otherUserId}, 用户名=${otherUsername}, 昵称=${otherNickname}, 头像=${otherAvatar}, 是否真实头像=${isRealAvatar}`)

      return {
        id: msg.conversationId || `${[currentUserId, otherUserId].sort().join('_')}`,
        name: otherUsername,
        nickname: otherNickname, // 使用后端返回的真实昵称
        avatar: otherAvatar,
        isOnline: false,
        isPinned: false,
        isMuted: false,
        lastMessage: { type: 'text', content: msg.message },
        lastMessageTime: new Date(msg.timestamp).getTime?.() || new Date(msg.timestamp).getTime() || Date.now(),
        unreadCount: 0,
        type: 'private',
        otherUsername: otherUsername,
        otherUserId: otherUserId // 添加对方用户ID
      }
    })

    console.log('=== 会话列表构建完成 ===')
    console.log('最终会话数量:', conversations.value.length)

    if (conversations.value.length === 0) {
      console.warn('⚠️ 会话列表为空，可能的原因:')
      console.warn('1. API返回数据为空')
      console.warn('2. 数据格式解析失败')
      console.warn('3. 用户没有任何会话记录')
      console.warn('原始API响应:', response)
      console.warn('解析后的数据:', rawList)
    }

    // 统计头像使用情况
    const avatarStats = conversations.value.reduce((stats, conv) => {
      if (conv.avatar === defaultAvatarUrl) {
        stats.default++
      } else {
        stats.real++
      }
      return stats
    }, { real: 0, default: 0 })

    console.log('头像统计:', `真实头像: ${avatarStats.real}个, 默认头像: ${avatarStats.default}个`)
  } catch (error) {
    console.error('加载会话列表失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 加载计数信息
const loadCounts = async () => {
  // 防止重复加载
  if (isLoadingCounts.value) return
  isLoadingCounts.value = true

  try {
    const [friendResponse, notificationResponse] = await Promise.all([
      friendApi.getFriendRequestCount(),
      messageApi.getNotificationCount()
    ])

    // 确保正确提取好友申请数量，与好友页面逻辑保持一致
    const friendCount = typeof friendResponse === 'number' ? friendResponse : (friendResponse?.data ?? 0)
    const notificationCountValue = typeof notificationResponse === 'number' ? notificationResponse : (notificationResponse?.count ?? 0)

    friendRequests.value = friendCount
    notificationCount.value = notificationCountValue

    console.log('好友申请数量:', friendRequests.value)
    console.log('通知数量:', notificationCount.value)
  } catch (error) {
    console.error('加载计数信息失败:', error)
    // 出错时设置默认值
    friendRequests.value = 0
    notificationCount.value = 0
  } finally {
    isLoadingCounts.value = false
  }
}

// 开启消息监听
const startMessageListener = () => {
  // 这里应该开启WebSocket连接或者轮询获取新消息
  console.log('开启消息监听')
}

// 停止消息监听
const stopMessageListener = () => {
  // 停止WebSocket连接或轮询
  console.log('停止消息监听')
}

// 下拉刷新
const onRefresh = async () => {
  console.log('🔄 开始下拉刷新')
  isRefreshing.value = true

  try {
    // 重新加载会话列表和头像信息
    await loadConversations()
    await loadCounts()

    uni.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 1500
    })
  } catch (error) {
    console.error('刷新失败:', error)
    uni.showToast({
      title: '刷新失败',
      icon: 'none',
      duration: 2000
    })
  } finally {
    isRefreshing.value = false
  }
}

// 手动刷新会话列表
const refreshConversations = async () => {
  console.log('🔄 手动刷新会话列表')

  try {
    isLoading.value = true
    await loadConversations()

    uni.showToast({
      title: '刷新完成',
      icon: 'success',
      duration: 1500
    })
  } catch (error) {
    console.error('刷新会话列表失败:', error)
    uni.showToast({
      title: '刷新失败',
      icon: 'none',
      duration: 2000
    })
  } finally {
    isLoading.value = false
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''

  const now = new Date()
  const messageTime = new Date(timestamp)
  const diffInHours = (now - messageTime) / (1000 * 60 * 60)

  if (diffInHours < 24) {
    return messageTime.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  } else if (diffInHours < 48) {
    return '昨天'
  } else {
    return messageTime.toLocaleDateString('zh-CN', {
      month: '2-digit',
      day: '2-digit'
    })
  }
}

// 格式化最后一条消息
const formatLastMessage = (message) => {
  if (!message) return ''

  switch (message.type) {
    case 'text':
      return message.content
    case 'image':
      return '[图片]'
    case 'voice':
      return '[语音]'
    case 'video':
      return '[视频]'
    case 'file':
      return '[文件]'
    case 'location':
      return '[位置]'
    default:
      return '[消息]'
  }
}

// 页面跳转
const goToSearch = () => {
  uni.navigateTo({
    url: '/pages/message/search'
  })
}

const goToFriends = () => {
  uni.navigateTo({
    url: '/pages/message/friends'
  })
}

const goToGroups = () => {
  uni.navigateTo({
    url: '/pages/message/groups'
  })
}

const goToNotifications = () => {
  uni.navigateTo({
    url: '/pages/message/notifications'
  })
}

const goToAiChat = () => {
  uni.navigateTo({
    url: '/pages/message/ai-chat'
  })
}

const openChat = (conversation) => {
  // 标记会话为已读
  markConversationAsRead(conversation.id)

  // 构建跳转URL，包含用户ID和昵称
  let url = `/pages/message/chat?conversationId=${conversation.id}&type=${conversation.type}&name=${encodeURIComponent(conversation.otherUsername || conversation.name)}&nickname=${encodeURIComponent(conversation.nickname || conversation.name)}&avatar=${encodeURIComponent(conversation.avatar || '')}`

  // 如果有对方用户ID，则添加到URL中
  if (conversation.otherUserId) {
    url += `&toUserId=${conversation.otherUserId}`
  }

  uni.navigateTo({ url })
}

// 显示添加菜单
const showAddMenu = () => {
  showAddModal.value = true
}

// 添加功能
const addFriend = () => {
  showAddModal.value = false
  uni.navigateTo({
    url: '/pages/message/add-friend'
  })
}

const createGroup = () => {
  showAddModal.value = false
  uni.navigateTo({
    url: '/pages/message/create-group'
  })
}

const joinGroup = () => {
  showAddModal.value = false
  uni.navigateTo({
    url: '/pages/message/join-group'
  })
}

// 会话操作
const showConversationMenu = (conversation) => {
  selectedConversation.value = conversation
  showContextMenu.value = true
}

const togglePin = async () => {
  try {
    await messageApi.togglePinConversation(selectedConversation.value.id)
    selectedConversation.value.isPinned = !selectedConversation.value.isPinned
    showContextMenu.value = false

    uni.showToast({
      title: selectedConversation.value.isPinned ? '已置顶' : '已取消置顶',
      icon: 'success'
    })
  } catch (error) {
    console.error('切换置顶失败:', error)
  }
}

const markAsRead = async () => {
  try {
    await markConversationAsRead(selectedConversation.value.id)
    showContextMenu.value = false
  } catch (error) {
    console.error('标记已读失败:', error)
  }
}

const markConversationAsRead = async (conversationId) => {
  try {
    // 找到该会话的对端用户信息
    const conv = conversations.value.find(c => c.id === conversationId)
    const userInfo = uni.getStorageSync('userInfo') || {}
    const currentUserId = userInfo?.id || userInfo?.userId

    console.log('🔖 标记会话已读:', {
      conversationId,
      currentUserId,
      otherUserId: conv?.otherUserId,
      otherUsername: conv?.otherUsername || conv?.name
    })

    if (conv && currentUserId) {
      // 优先尝试基于ID的方式，失败则降级到用户名方式
      let markReadSuccess = false

      if (conv.otherUserId && currentUserId) {
        try {
          // 确保参数是有效的数字
          const fromUserIdNum = parseInt(conv.otherUserId)
          const toUserIdNum = parseInt(currentUserId)

          if (!isNaN(fromUserIdNum) && !isNaN(toUserIdNum)) {
            console.log('🔖 尝试使用ID方式标记已读:', fromUserIdNum, '->', toUserIdNum)
            await messageApi.markMessagesAsReadByIds(fromUserIdNum, toUserIdNum)
            console.log('✅ ID方式标记已读成功')
            markReadSuccess = true
          } else {
            console.warn('⚠️ 用户ID不是有效数字，降级到用户名方式')
          }
        } catch (error) {
          console.warn('⚠️ ID方式标记已读失败，降级到用户名方式:', error.message)
        }
      }

      // 如果ID方式失败，使用用户名方式
      if (!markReadSuccess && (conv.otherUsername || conv.name)) {
        console.log('🔖 使用用户名方式标记已读')
        const currentUsername = userInfo?.username || userInfo?.nickname || 'user'
        const fromUser = conv.otherUsername || conv.name
        console.log('🔖 标记已读参数:', { fromUser, toUser: currentUsername })
        await messageApi.markMessagesAsRead(fromUser, currentUsername)
        console.log('✅ 用户名方式标记已读成功')
        markReadSuccess = true
      }

      if (!markReadSuccess) {
        console.warn('⚠️ 无法标记已读：缺少必要的用户信息')
        return
      }
    } else {
      console.warn('⚠️ 无法标记已读：缺少会话信息或当前用户ID')
      return
    }

    // 更新本地数据
    if (conv) {
      conv.unreadCount = 0
      console.log('✅ 本地未读数已清零')
    }

    // 更新全局未读数
    store.updateUnreadCount && store.updateUnreadCount()
    console.log('✅ 全局未读数已更新')

  } catch (error) {
    console.error('❌ 标记已读失败:', error)
  }
}

const muteConversation = async () => {
  try {
    await messageApi.muteConversation(selectedConversation.value.id, !selectedConversation.value.isMuted)
    selectedConversation.value.isMuted = !selectedConversation.value.isMuted
    showContextMenu.value = false

    uni.showToast({
      title: selectedConversation.value.isMuted ? '已开启免打扰' : '已关闭免打扰',
      icon: 'success'
    })
  } catch (error) {
    console.error('设置免打扰失败:', error)
  }
}

const deleteConversation = () => {
  uni.showModal({
    title: '删除会话',
    content: '确定要删除此会话吗？删除后聊天记录将清空。',
    confirmText: '删除',
    cancelText: '取消',
    confirmColor: '#ff4757',
    success: async (res) => {
      if (res.confirm) {
        try {
          await messageApi.deleteConversation(selectedConversation.value.id)

          // 从列表中移除
          const index = conversations.value.findIndex(conv => conv.id === selectedConversation.value.id)
          if (index > -1) {
            conversations.value.splice(index, 1)
          }

          showContextMenu.value = false
          uni.showToast({
            title: '已删除',
            icon: 'success'
          })
        } catch (error) {
          console.error('删除会话失败:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

const clearAllConversations = () => {
  uni.showModal({
    title: '清空会话',
    content: '确认要清除吗，聊天记录也会一并删除',
    confirmText: '确认清除',
    cancelText: '取消',
    confirmColor: '#ff4757',
    success: async (res) => {
      if (res.confirm) {
        try {
          // 显示加载状态
          uni.showLoading({
            title: '清除中...'
          })

          // 获取当前用户信息
          const userInfo = uni.getStorageSync('userInfo') || {}
          const username = userInfo?.username || userInfo?.nickname || userInfo?.email

          if (!username) {
            uni.hideLoading()
            uni.showToast({
              title: '用户信息获取失败',
              icon: 'none'
            })
            return
          }

          // 调用后端API清空聊天记录
          await messageApi.clearAllChatMessages(username)

          // 清空前端会话列表
          conversations.value = []

          uni.hideLoading()
          uni.showToast({
            title: '清除成功',
            icon: 'success'
          })

          console.log('✅ 所有聊天记录已清空')

        } catch (error) {
          uni.hideLoading()
          console.error('❌ 清空聊天记录失败:', error)

          uni.showToast({
            title: '清除失败',
            icon: 'none',
            duration: 2000
          })
        }
      }
    }
  })
}

// 头像加载错误处理
const onAvatarError = (e) => {
  console.log('会话头像加载失败，使用默认头像')
  console.log('失败的头像URL:', e.target.src)

  // 直接使用默认头像，不生成基于用户名的头像
  e.target.src = 'https://ts1.tc.mm.bing.net/th/id/OIP-C.4qE6UmzbSk0mCOn2uWMELAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3'
}




</script>

<style lang="scss" scoped>
.message-container {
  background: #FAFAFA;
  min-height: 100vh;
}

.search-header {
  background: #FFFFFF;
  padding: 20px 15px 10px 15px;
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid #F0F0F0;
}

.search-box {
  flex: 1;
  background: #F8F9FA;
  border-radius: 20px;
  padding: 8px 15px;
  display: flex;
  align-items: center;
  gap: 8px;

  .search-icon {
    font-size: 14px;
    font-weight: 600;
    color: #6C757D;
    font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  }

  .search-placeholder {
    font-size: 14px;
    color: #999999;
  }
}

.add-btn {
  width: 36px;
  height: 36px;
  background: #F8F9FA;
  border: 1px solid #E9ECEF;
  border-radius: 18px;
  display: flex;
  align-items: center;
  justify-content: center;

  .add-icon {
    font-size: 18px;
    font-weight: 300;
    color: #ADB5BD;
    font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  }
}

.function-section {
  background: #FFFFFF;
  padding: 15px;
  margin-bottom: 10px;
}

.function-list {
  display: flex;
  justify-content: space-around;
}

.function-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;

  .function-icon {
    width: 50px;
    height: 50px;
    border-radius: 25px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 8px;

    &.friends {
      background: #F8F9FA;
      border: 1px solid #E9ECEF;
    }

    &.ai-chat {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;
    }

    &.notifications {
      background: #F8F9FA;
      border: 1px solid #E9ECEF;
    }
  }

  /* 图标图片样式 */
  .icon-image {
    width: 24px;
    height: 24px;
  }

  .function-name {
    font-size: 12px;
    color: #666666;
  }

  .badge {
    position: absolute;
    top: -5px;
    right: 0;
    background: #DC3545;
    color: #FFFFFF;
    font-size: 10px;
    padding: 2px 6px;
    border-radius: 10px;
    min-width: 16px;
    text-align: center;
  }
}

.conversation-section {
  background: #FFFFFF;
  flex: 1;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  border-bottom: 1px solid #F0F0F0;

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #333333;
  }

  .header-actions {
    display: flex;
    align-items: center;
    gap: 10px;
  }



  .refresh-btn {
    font-size: 14px;
    color: #007AFF;
    margin-right: 8px;
    padding: 4px 8px;
    border-radius: 4px;
    background: #F0F8FF;
  }

  .clear-btn {
    font-size: 14px;
    color: #999999;
  }
}

.conversation-scroll {
  height: calc(100vh - 200px); /* 根据实际需要调整高度 */
  padding: 0 15px;
}

.conversation-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #F8F9FA;
  position: relative;

  &.pinned {
    background: #fffbf0;
  }

  &:active {
    background: #F8F9FA;
  }
}

.avatar-container {
  position: relative;
  margin-right: 12px;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 25px;
}

.online-status {
  position: absolute;
  bottom: 2px;
  right: 2px;
  width: 12px;
  height: 12px;
  background: #28A745;
  border: 2px solid #FFFFFF;
  border-radius: 50%;
}

.conversation-info {
  flex: 1;
  min-width: 0;
}

.conversation-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
}

.conversation-name {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.conversation-time {
  font-size: 12px;
  color: #999999;
  flex-shrink: 0;
}

.conversation-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.last-message {
  font-size: 14px;
  color: #666666;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.unread-badge {
  background: #DC3545;
  color: #FFFFFF;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 18px;
  text-align: center;
  flex-shrink: 0;
  margin-left: 8px;
}

.pin-icon {
  position: absolute;
  top: 15px;
  right: 15px;
  font-size: 8px;
  color: #6C757D;
  font-weight: 600;
}

.empty-state {
  padding: 50px 20px;
}

.add-modal,
.context-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-menu {
  background: #FFFFFF;
  border-radius: 12px;
  padding: 20px;
  margin: 0 40px;
  min-width: 200px;
}

.add-option {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #F0F0F0;

  &:last-child {
    border-bottom: none;
  }

  .option-icon {
    font-size: 16px;
    font-weight: 600;
    margin-right: 12px;
    color: #6C757D;
    font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  }

  .option-text {
    font-size: 16px;
    color: #333333;
  }
}



.context-menu {
  background: #FFFFFF;
  border-radius: 8px;
  margin: 0 40px;
  overflow: hidden;
}

.menu-option {
  padding: 15px 20px;
  border-bottom: 1px solid #F0F0F0;

  &:last-child {
    border-bottom: none;
  }

  &.delete {
    .option-text {
      color: #DC3545;
    }
  }

  &:active {
    background: #F8F9FA;
  }

  .option-text {
    font-size: 16px;
    color: #333333;
  }
}
</style>
